﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using VM.Common.Result;

namespace VM.WebCore.Jwt
{
    public class HSJWTService : IJWTService
    {
        private JWTTokenOptions _JWTTokenOptions = null;
        private readonly IHttpContextAccessor _HttpContextAccessor;

        
        public HSJWTService(IOptions<JWTTokenOptions> options, IHttpContextAccessor httpContextAccessor)
        {
            _JWTTokenOptions = options.Value;
            _HttpContextAccessor = httpContextAccessor;
        }


        /// <summary>
        /// JWT是个Token---
        /// 1   就是传递用户信息
        /// 2   加密钥---签名
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public string GetToken(string name)
        {
            var claims = new[]
            {
                 new Claim("Name", name),
                 new Claim("id", "11"),
                 #region 为授权添加
                 new Claim(ClaimTypes.Name, "Eleven"),
                 new Claim("EMail", "57265177@qq.com"),
                 new Claim(ClaimTypes.Email, "xuyang@zhaoxiedu.net"),
                 new Claim("Account", "Administrator"),
                 new Claim("Age", "35"),
                 new Claim("Mobile", "18664876666"),
                 new Claim(ClaimTypes.Role,"Admin"),
                 new Claim("Role", "User"),//这个不能默认角色授权，动态角色授权
                 new Claim("Sex", "1")//各种信息拼装
	                #endregion
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecurityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: _JWTTokenOptions.Issuer,
                audience: _JWTTokenOptions.Audience,
                claims: claims,
                expires: DateTime.Now.AddSeconds(60 * 10),//10分钟有效期
                notBefore: DateTime.Now,//立即生效  DateTime.Now.AddMilliseconds(30),//30s后有效
                signingCredentials: creds
                );
            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            return returnToken;
        }


        public   string AnaliseToken(string jwtToken, string KeyName)
        {


            // 创建一个 JwtSecurityTokenHandler 对象，用于验证和解析 JWT
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            // 创建一个 TokenValidationParameters 对象，用于配置验证器
            TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                ValidateIssuer = false,          // 验证发行者（Issuer）
                ValidateAudience = false,        // 验证受众（Audience）
                ValidateLifetime = false,        // 验证过期时间（Expiration time）
                ValidateIssuerSigningKey = true // 验证签名密钥（Signing key）
                                                // 可以根据你的具体需求进行更多的验证参数配置
            };

            // 这里假设你的签名密钥是一个字符串
            string signingKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB";

            // 将签名密钥转换为字节数组
            byte[] signingKeyBytes = Encoding.UTF8.GetBytes(signingKey);

            // 创建一个 SecurityKey 对象，用于验证签名
            SecurityKey securityKey = new SymmetricSecurityKey(signingKeyBytes);

            // 设置验证参数的签名密钥
            validationParameters.IssuerSigningKey = securityKey;
             
            try
            {
                // 验证并解析 JWT
                var claimsPrincipal = tokenHandler.ValidateToken(jwtToken, validationParameters, out var validatedToken);

                // 获取解析后的 Token 内容
                var claims = claimsPrincipal.Claims;
                // 查找 Claim 类型为 "id" 的值
                string claimValue = claims.FirstOrDefault(c => c.Type == KeyName)?.Value;

                if (claimValue != null)
                {
                    return claimValue;
                }
                else
                {
                    return "";
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine($"代码解析jwt错误: {ex.Message}");
                return "";
            }
        }



        /// <summary>
        /// 根据传入的请求头的authInfo信息，获取userId信息
        /// </summary>
        /// <param name="AuthInfo"></param>
        /// <returns></returns>
        public int GetUserIdByAuthInfoStr()
        {
            //获取到header 内的用户信息进行解析
            var authorizationHeader = _HttpContextAccessor.HttpContext.Request.Headers["Authorization"];
            //解析jwt
            string tokenInfo = authorizationHeader.ToString().Replace("bearer ", "").Replace("Bearer ", "");
            var AESId =AnaliseToken(tokenInfo, "id");
            //解析userid
            int UserId = Convert.ToInt32(AESUntil.Decrypt(AESId));
            return UserId;
        }
    }
}
